import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import s from './IpPortView.module.css';

export default function IpPortView({
	className,
	ip,
	ports = [],
	onChangeViewToHostIp,
}) {
	const portRad = 360 / ports.length;

	return (
		<g className={cn(className, s.ipPortsView)}>
			<rect
				width="100%"
				height="100%"
				x="-50%"
				y="-50%"
				fill="transparent"
				onClick={onChangeViewToHostIp}
			/>
			<g className={s.links}>
				{ports.map(({ port, service }, idx) => {
					const radius = portRad * idx - 90;
					const rad = (radius * Math.PI) / 180;
					const x = Math.cos(rad) * 300;
					const y = Math.sin(rad) * 300;
					const position = radius > 90 || radius < -90 ? 'left' : 'right';

					return (
						<g key={port} className={s.port}>
							<line className={s.line} x1={0} y1={0} x2={x} y2={y} />
							<circle
								r="5"
								className={s.anchor}
								transform={`translate(${Math.cos(rad) * 120},${
									Math.sin(rad) * 120
								})`}
							/>
							<text
								className={s.label}
								dx={position === 'right' ? '10px' : '-10px'}
								dy="0.3em"
								textAnchor={position === 'right' ? 'start' : 'end'}
								transform={`translate(${Math.cos(rad) * 120},${
									Math.sin(rad) * 120
								}) rotate(${position === 'right' ? radius : radius - 180})`}
							>
								{service}
							</text>
							<g className={s.node} transform={`translate(${x},${y})`}>
								<circle className={s.archor} r="30" />
								<text dy="0.5em" textAnchor="middle">
									{port}
								</text>
							</g>
						</g>
					);
				})}
			</g>
			<g className={s.ip}>
				<circle r="100" />
				<text textAnchor="middle" dy="0.5em">
					{ip.name}
				</text>
			</g>
		</g>
	);
}

IpPortView.propTypes = {
	className: PropTypes.string,
	ip: PropTypes.shape({
		name: PropTypes.string.isRequired,
	}),
	ports: PropTypes.arrayOf(
		PropTypes.shape({
			name: PropTypes.string.isRequired,
		})
	),
	onChangeViewToHostIp: PropTypes.func.isRequired,
};

IpPortView.defaultProps = {
	className: s.ipPortView,
};
